#!/usr/bin/env python

import wsgiref.handlers
import os
import time
import xml.dom.minidom
from douban import Constants
from douban import oAuth
from douban import cookie
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.api import urlfetch


class EntryModel:
    author_name = ""
    author_icon = ""
    title = ""
    content = ""

class MainPage(webapp.RequestHandler):
    def get(self):        
        isRedirect = False
                        
        oauth_token_secret = self.request.get('oauth_token_secret')        
        oauth_token_secret = cookie.getCookie(self, oauth_token_secret, "oauth_token_secret")        
        if oauth_token_secret is None:
            isRedirect = True

        oauth_token = self.request.get('oauth_token')        
        oauth_token = cookie.getCookie(self, oauth_token, "oauth_token")        
        if oauth_token is None:
            isRedirect = True            
            
        douban_user_id = self.request.get('douban_user_id')        
        douban_user_id = cookie.getCookie(self, douban_user_id, "douban_user_id")        
        if douban_user_id is None:
            isRedirect = True

        if isRedirect == True:
            self.redirect("/douban")
        else:
            crtPage = self.request.get('crtpage')
            if not crtPage:
                crtPage = 1
                
            start_index = (int(crtPage) -1) * 5 + 1
            
            oauth_consumer_key = Constants.API_KEY
            oauth_signature_method = Constants.SIGNATURE_METHOD                
            api_key_secret = Constants.API_KEY_SECRET        
            key = '%s&%s' % (oAuth.escape(api_key_secret), oAuth.escape(oauth_token_secret))
            oauth_signature = oAuth.escape(key)    
            oauth_timestamp = str(int(time.time()))
            oauth_nonce = oAuth.generate_nonce(8)

            con_URL = ["http://api.douban.com/people/",
                          douban_user_id,
                          "/miniblog/contacts?start-index=",
                          str(start_index),
                          "&max-results=5",
                          "&amp;oauth_consumer_key=",
                          oauth_consumer_key,
                          "&amp;oauth_token=",
                          oauth_token,
                          "&amp;oauth_signature_method=",
                          oauth_signature_method,
                          "&amp;oauth_signature=",
                          oauth_signature,
                          "&amp;oauth_timestamp=",
                          oauth_timestamp,
                          "&amp;oauth_nonce=",
                          oauth_nonce
                         ]

            url = ''.join(con_URL)

            entryList = []            
            username =  ""
            err = False
            try:
                result = urlfetch.fetch(url)
                if result.status_code == 200:            
                    xmlStr = result.content
                    dom = xml.dom.minidom.parseString(xmlStr)
                    
                    username = dom.getElementsByTagName("name")[0].childNodes[0].data
                    
                    entries = dom.getElementsByTagName("entry")
                    
                    
                    for entry in entries:
                        
                        entryModel = EntryModel()
                        titleObj = entry.getElementsByTagName("title")
                        contentObj = entry.getElementsByTagName("content")
                        if titleObj and contentObj:
                            title = titleObj[0].childNodes[0].data
                            author = entry.getElementsByTagName("author")[0]
                            author_name = author.getElementsByTagName("name")[0].childNodes[0].data
                            author_icon = author.getElementsByTagName("link")[2].getAttribute("href")                        
                            content = contentObj[0].childNodes[0].data                        
                            content = content.replace('<a ', '<a target="_blank" ', -1)                    
                            entryModel.author_icon = author_icon
                            entryModel.author_name = author_name
                            entryModel.content = content
                            entryModel.title = title

                            entryList.append(entryModel)                            
                        
                    #self.response.headers["Content-Type"] = "text/xml; charset=utf-8" 
                    #self.response.out.write(xmlStr)
                else:
                    err = True
            except:
                err = True                

            nextPage = int(crtPage) + 1

            prePage = int(crtPage) - 1
            if prePage <= 0:
                prePage = False

            template_values = {
                "username" : username,
                "entryList" : entryList,
                "nextPage" : nextPage,
                "prePage" : prePage,
                "crtPage" : crtPage,
                "err" : err
            }
                    
            path = os.path.join(os.path.dirname(__file__), 'index.html')           
            self.response.out.write(template.render(path, template_values))
    
    
def main():
    application = webapp.WSGIApplication([('/douban/miniblog/contact', MainPage)],debug=True)    
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
    main() 

